import datetime
import os

import pymysql
from PySide6 import QtCore
from PySide6.QtCore import QUrl, QPoint
from PySide6.QtGui import Qt, QKeySequence
from PySide6.QtWebChannel import QWebChannel
from PySide6.QtWebEngineWidgets import QWebEngineView
from PySide6.QtWidgets import QMainWindow, QMessageBox, QMenu, QWidget, QTabWidget, QToolButton, QListWidgetItem, \
    QComboBox, QLabel, QPlainTextEdit

from global_variables import GlobalVariables
from util import common
from util.python_js import JsPython

TABLE_INFORMATION_DEBUG = False
DEBUG_PORT = '5589'
DEBUG_URL = 'http://127.0.0.1:%s' % DEBUG_PORT
if TABLE_INFORMATION_DEBUG:
    os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = DEBUG_PORT


class TableInformation(QMainWindow):
    def __init__(self, app):
        super().__init__()
        self.app = app
        self.mysqldb = self.app.mysqldb
        self.ui = app.ui

        self.init()

    def init(self):
        self.ui.reset_auto_increment_button.clicked.connect(self.reset_auto_increment_button_clicked)

        # webview与python交互
        self.web_view_js_channel()

        if self.get_table_name() is None:
            self.ui.reset_auto_increment_button.setEnabled(False)

    def get_table_name(self):
        item = self.ui.table_list.currentItem()
        if isinstance(item, QListWidgetItem):
            return item.text()
        return None

    def reset_auto_increment_button_clicked(self):
        result = QMessageBox.question(self, '确认', f'是否自增ID')
        if result != QMessageBox.StandardButton.Yes:
            return
        
        table_name = self.get_table_name()
        if table_name is None:
            return
        self.app.mysqldb.reset_auto_increment(table_name)

    def tab_table_information_clear(self):
        self.handler.python_set_sql("")
        self.ui.reset_auto_increment_button.setEnabled(False)

    def tab_table_information_fill_data(self, table_name: str):
        button: QToolButton = self.ui.reset_auto_increment_button
        button.setEnabled(True)
        data = self.app.mysqldb.show_create_table(table_name)
        key = 'Create Table'
        if key not in data:
            return
        sql: str = data[key]
        self.handler.python_set_sql(sql.replace("\n", ' '))

        select_database = self.ui.database_select.currentText()
        data = self.mysqldb.table_information(select_database, table_name)
        if data is None:
            return
        comboBox_table_engine: QComboBox = self.ui.comboBox_table_engine
        comboBox_table_engine.addItems(GlobalVariables.LIST_DATABASE_ENGINE)
        for engine in GlobalVariables.LIST_DATABASE_ENGINE:
            if engine.upper() == data['ENGINE'].upper():
                comboBox_table_engine.setCurrentText(engine)
        list_collation = []
        list_charset = []
        for collation, charset in GlobalVariables.MAP_COLLECTION_CHARSET.items():
            list_collation.append(collation)
            list_charset.append(charset)
        self.ui.comboBox_table_encoding.addItems(list(set(list_charset)))
        self.ui.comboBox_table_collation.addItems(list(set(list_collation)))

        self.ui.comboBox_table_collation.setCurrentText(data['TABLE_COLLATION'])
        self.ui.comboBox_table_encoding.setCurrentText(GlobalVariables.MAP_COLLECTION_CHARSET.get(data['TABLE_COLLATION']))

        if isinstance(data['CREATE_TIME'], datetime.datetime):
            create_time = data['CREATE_TIME'].strftime('%Y-%m-%d %H:%M:%S')
        else:
            create_time = '-'
        self.ui.label_4_left_3_created_at.setText(create_time)

        if isinstance(data['UPDATE_TIME'], datetime.datetime):
            update_time = data['UPDATE_TIME'].strftime('%Y-%m-%d %H:%M:%S')
        else:
            update_time = '-'
        self.ui.label_4_left_2_updated_at.setText(update_time)

        self.ui.label_2_number_of_rows.setText(str(data['TABLE_ROWS']))
        self.ui.label_6_row_format.setText(data['ROW_FORMAT'])
        self.ui.label_3_avg_row_length.setText(str(data['AVG_ROW_LENGTH']))
        self.ui.label_7_auto_increment.setText(str(data['AUTO_INCREMENT']))
        self.ui.label_4_left_4_data_size.setText(str(data['DATA_LENGTH']))
        self.ui.label_4_left_10_max_data_size.setText(str(data['MAX_DATA_LENGTH']))
        self.ui.label_4_left_7_index_size.setText(str(data['INDEX_LENGTH']))
        self.ui.label_4_left_11_free_data_size.setText(str(data['DATA_FREE']))
        self.ui.plainTextEdit_table_comment.setPlainText(data['TABLE_COMMENT'])


    def web_view_js_channel(self):
        self.add_web_view()
        web: QWebEngineView = self.ui.create_table_sql

        # 右键菜单(禁用)
        web.setContextMenuPolicy(Qt.ContextMenuPolicy.NoContextMenu)
        # web.customContextMenuRequested.connect(lambda p: self.show_menu(p, web))

        self.app.jsTableChannel = channel = QWebChannel(self)
        self.app.jsTableHandler = handler = JsPython(self.app, web)
        channel.registerObject('py', handler)
        web.page().setWebChannel(channel)
        web.load(QUrl.fromLocalFile(GlobalVariables.PROJECT_BASE_PATH.replace(os.sep, '/') + 'sql-editor/index.html'))
        self.handler = handler

        if TABLE_INFORMATION_DEBUG:
            os.environ['QTWEBENGINE_REMOTE_DEBUGGING'] = DEBUG_PORT
            # 添加调试
            view: QWebEngineView = QWebEngineView(self.ui.groupBox_9)
            view.setWindowTitle('Web Inspector')
            view.load(QUrl(DEBUG_URL))
            view.setFixedHeight(0)
            view.setFixedWidth(0)
            web.loadFinished.connect(lambda ok: self.handle_html_loaded(ok, web, view))

    def add_web_view(self):
        self.ui.create_table_sql = QWebEngineView(self.ui.groupBox_9)
        self.ui.create_table_sql.setObjectName(u"create_table_sql")
        self.ui.create_table_sql.setEnabled(True)
        self.ui.create_table_sql.setUrl(QUrl(u"about:blank"))
        self.ui.horizontalLayout_20.addWidget(self.ui.create_table_sql)

    # 加载完成后显示调试网页
    def handle_html_loaded(self, ok: bool, page: QWebEngineView, debug_page: QWebEngineView):
        if ok:
            page.page().setDevToolsPage(debug_page.page())
            debug_page.show()

    # SQL语句点击格式化
    def format_sql_query_button_clicked(self):
        self.handler.python_format_sql()
